<template>
  <div class="chart-container">
    <div class="chart-header">
      <h3>{{ title }}</h3>
      <el-select
        v-model="timeRange"
        size="small"
        @change="handleTimeRangeChange"
        v-if="showTimeRangeSelector"
      >
        <el-option label="最近1小时" value="1h" />
        <el-option label="最近24小时" value="24h" />
      </el-select>
    </div>
    <div class="chart" :id="chartId"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  title: {
    type: String,
    required: true,
  },
  chartId: {
    type: String,
    required: true,
  },
  timeRange: {
    type: String,
    default: "1h",
  },
  chartType: {
    type: String,
    default: "line", // line|bar|gauge|pie 等
  },
  showTimeRangeSelector: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(["timeRangeChange"]);

const timeRange = ref(props.timeRange);
let chartInstance = null;

const handleTimeRangeChange = (value) => {
  emit("timeRangeChange", value);
  updateChartData();
};

const initChart = () => {
  const chartDom = document.getElementById(props.chartId);
  if (!chartDom) return;

  chartInstance = echarts.init(chartDom);
  updateChartData();
};

const updateChartData = () => {
  const option = getChartOption();
  chartInstance && chartInstance.setOption(option);
};

const getChartOption = () => {
  // 根据不同的图表ID返回不同的配置
  switch (props.chartId) {
    case "cpuChart":
      return getLineChartOption(
        "CPU利用率",
        "#1890ff",
        [10, 20, 13, 25, 18, 15, 12],
        "%"
      );

    case "memoryChart":
      return getLineChartOption(
        "内存利用率",
        "#ff9900",
        [8, 15, 10, 18, 12, 9, 14],
        "%"
      );

    case "responseTimeChart":
      return getLineChartOption(
        "响应时间",
        "#52c41a",
        [5, 8, 6, 9, 7, 5, 6],
        "ms"
      );

    case "unreachableChart":
      return getLineChartOption(
        "不可达比率",
        "#f5222d",
        [2, 5, 3, 6, 4, 3, 5],
        "%"
      );

    case "speedChart":
      return getBarChartOption();

    case "configChangeChart":
      return getGaugeChartOption();

    default:
      return getLineChartOption(
        props.title,
        "#1890ff",
        [10, 15, 12, 18, 14, 10, 13]
      );
  }
};

// 线性图通用配置
const getLineChartOption = (name, color, data, unit = "") => {
  return {
    tooltip: {
      trigger: "axis",
      formatter: `{b}<br/>{a0}: {c0}${unit}`,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: generateXAxisData(),
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: `{value}${unit}`,
      },
    },
    series: [
      {
        name,
        type: "line",
        data,
        itemStyle: { color },
        lineStyle: { width: 2, color },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(24, 144, 255, 0.3)" },
            { offset: 1, color: "rgba(24, 144, 255, 0)" },
          ]),
        },
      },
    ],
  };
};

// 柱状图配置 (用于 speedChart)
const getBarChartOption = () => {
  return {
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
      name: "速度 (Mbps)",
      max: 10,
    },
    yAxis: {
      type: "category",
      data: ["GE0/0/24", "GE1/0/1", "GE2/0/3", "GE3/0/2", "GE4/0/5"],
    },
    series: [
      {
        name: "速度",
        type: "bar",
        data: [7.5],
        itemStyle: {
          color: (params) => {
            const colors = [
              "#1890ff",
              "#52c41a",
              "#722ed1",
              "#fa8c16",
              "#fadb14",
            ];
            return colors[params.dataIndex % colors.length];
          },
        },
        label: {
          show: true,
          position: "right",
          formatter: "{c} Mbps",
        },
      },
    ],
  };
};

// 仪表盘配置 (用于 configChangeChart)
const getGaugeChartOption = () => {
  return {
    tooltip: {
      formatter: "{a} <br/>{b} : {c}次",
    },
    series: [
      {
        name: "配置文件变更",
        type: "gauge",
        min: 0,
        max: 20,
        progress: {
          show: true,
          width: 18,
          itemStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: "#1890ff",
                },
                {
                  offset: 1,
                  color: "#52c41a",
                },
              ],
            },
          },
        },
        axisLine: {
          lineStyle: {
            width: 18,
          },
        },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: {
          distance: 25,
          color: "#999",
          fontSize: 12,
        },
        detail: {
          valueAnimation: true,
          fontSize: 24,
          offsetCenter: [0, "70%"],
          formatter: "{value}次",
          color: "#333",
        },
        data: [
          {
            value: 12,
            name: "变更次数",
          },
        ],
      },
    ],
  };
};

const generateXAxisData = () => {
  return timeRange.value === "1h"
    ? ["00:00", "00:15", "00:30", "00:45", "01:00"]
    : Array.from({ length: 24 }, (_, i) => `${i}:00`);
};

const handleResize = () => {
  chartInstance && chartInstance.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
});

watch(
  () => props.timeRange,
  (newVal) => {
    timeRange.value = newVal;
    updateChartData();
  }
);
</script>

<style lang="scss" scoped>
.chart-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid #eaeaea;
  height: 100%;

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
      font-weight: 500;
    }
  }
  .el-select {
    width: 114px;
  }
  .chart {
    height: 240px;
    width: 100%;
  }
}
</style>